import eventlet
import socketio
from flask import Flask
from flask_socketio import send, emit, Namespace, SocketIO
import random
import json

app = Flask(__name__, template_folder="templates")

app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, engineio_logger=True, logger=True, cors_allowed_origins='http://localhost:3000')


class RosBridgeNamespace(Namespace):
    # def __init__(self, socketio, namespace=None):
    #     super().__init__(namespace=namespace)
    #     self.socketio = socketio

    def on_connect(self):
        print('############## some ros connect')

    def on_disconnect(self):
        print('disconnect')

    def send_to_front(self, data):
        self.socketio.emit('data',
                           json.dumps(data),
                           namespace='/rosbridge', broadcast=True)

    def send_to_rosbridge(self, data):
        self.socketio.emit('diegoserver',
                           data,
                           namespace='/rosbridge', broadcast=True)

    def on_rosbridge(self, data):  # response for rosbridge
        self.send_to_front(data)

    def on_operation(self, data):  # response for web client
        print('**************** receive operation message from web roblibjs client')
        self.send_to_rosbridge(data)


socketio.on_namespace(RosBridgeNamespace('/channel_A'))

if __name__ == '__main__':
    SERVER_ADDRESS = ('127.0.0.1', 8000)
    sock = eventlet.listen(SERVER_ADDRESS)
    eventlet.wsgi.server(sock, app)
